package com.ruoyi.business.service.impl;

import java.util.List;

import com.ruoyi.business.domain.JtAppUser;
import com.ruoyi.business.domain.JtDistributorRating;
import com.ruoyi.business.service.IJtAppUserService;
import com.ruoyi.business.service.IJtDistributorRatingService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.JtDistributorMapper;
import com.ruoyi.business.domain.JtDistributor;
import com.ruoyi.business.service.IJtDistributorService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 分销商信息Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-03-31
 */
@Service
public class JtDistributorServiceImpl implements IJtDistributorService 
{
    @Autowired
    private JtDistributorMapper jtDistributorMapper;
    @Autowired
    private IJtDistributorRatingService jtDistributorRatingService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IJtAppUserService jtAppUserService;

    /**
     * 查询分销商信息
     * 
     * @param distributorId 分销商信息主键
     * @return 分销商信息
     */
    @Override
    public JtDistributor selectJtDistributorByDistributorId(Long distributorId)
    {
        return jtDistributorMapper.selectJtDistributorByDistributorId(distributorId);
    }

    /**
     * 查询分销商信息列表
     * 
     * @param jtDistributor 分销商信息
     * @return 分销商信息
     */
    @Override
    public List<JtDistributor> selectJtDistributorList(JtDistributor jtDistributor)
    {
        return jtDistributorMapper.selectJtDistributorList(jtDistributor);
    }

    /**
     * 新增分销商信息
     * 
     * @param jtDistributor 分销商信息
     * @return 结果
     */
    @Override
    public int insertJtDistributor(JtDistributor jtDistributor)
    {
        jtDistributor.setCreateTime(DateUtils.getNowDate());
        return jtDistributorMapper.insertJtDistributor(jtDistributor);
    }

    /**
     * 修改分销商信息
     * 
     * @param jtDistributor 分销商信息
     * @return 结果
     */
    @Override
    public int updateJtDistributor(JtDistributor jtDistributor)
    {
        jtDistributor.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtDistributor.setUpdateTime(DateUtils.getNowDate());
        return jtDistributorMapper.updateJtDistributor(jtDistributor);
    }


    /**
     * 修改分销商信息
     *
     * @param jtDistributor 分销商信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult auditJtDistributor(JtDistributor jtDistributor)
    {
        JtDistributor jtDistributorDb = selectJtDistributorByDistributorId(jtDistributor.getDistributorId());

        if(jtDistributorDb.getAuditStatus() != 0){
            return AjaxResult.error("已审核！");
        }

        Object remarkObj = jtDistributor.getParams().get("remark");
        String remark = "";
        if(remarkObj != null) {
            remark = (String) remarkObj;
        }
        if(jtDistributorDb.getRating() != null){
            if(jtDistributor.getRating() == null){
                //修改为空
                addJtDistributorRating(jtDistributor.getDistributorId(), jtDistributor.getRating(), remark);
            } else {
                if(!jtDistributor.getRating().equals(jtDistributorDb.getRating())){
                    //修改值
                    addJtDistributorRating(jtDistributor.getDistributorId(), jtDistributor.getRating(), remark);
                }
            }
        } else {
            if(jtDistributor.getRating() != null){
                //第一次打分
                addJtDistributorRating(jtDistributor.getDistributorId(), jtDistributor.getRating(), remark);
            }
        }
        if(jtDistributor.getAuditStatus() == 1) {
            jtDistributor.setAuditBy(ShiroUtils.getSysUser().getUserName());
        }
        int rows = updateJtDistributor(jtDistributor);
        if(rows > 0){
            return AjaxResult.error("审核成功！");
        } else {
            return AjaxResult.error("审核失败！");
        }
    }

    private int addJtDistributorRating(Long distributorId, Integer rating, String remark){
        JtDistributorRating entity = new JtDistributorRating();
        entity.setDistributorId(distributorId);
        entity.setRater(ShiroUtils.getSysUser().getUserName());
        entity.setRating(rating);
        entity.setRemark(remark);
        return jtDistributorRatingService.insertJtDistributorRating(entity);
    }

    /**
     * 创建系统后台 分销商用户
     * @param distributorId
     * @return
     */
    @Transactional
    @Override
    public AjaxResult createSysUser(Long distributorId){
        JtDistributor distributorDb = selectJtDistributorByDistributorId(distributorId);
        JtAppUser jtAppUser = jtAppUserService.selectJtAppUserByUserId(distributorDb.getUserId());
        if(jtAppUser.getSysUserId() != null) {
            return AjaxResult.error("已绑定后台系统用户！");
        }
        SysUser user = new SysUser();
        user.setUserName(distributorDb.getDistributorName());
        user.setLoginName(jtAppUser.getPhoneNumber());
        user.setPhonenumber(jtAppUser.getPhoneNumber());
        user.setEmail(distributorDb.getEmail());
        user.setPassword("88888888");
        user.setDeptId(102L);//分销商   部门
        user.setRoleIds(new Long[]{4L});//分销商 角色
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!sysUserService.checkLoginNameUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysUserService.checkPhoneUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        user.setCreateBy(ShiroUtils.getSysUser().getUserName());
        int rows = sysUserService.insertUser(user);
        if(rows > 0){

            jtAppUser.setSysUserId(user.getUserId());
            jtAppUserService.updateJtAppUser(jtAppUser);
            return AjaxResult.success("创建分销商成功！");
        } else {
            return AjaxResult.error("创建分销商失败");
        }
    }

    public String encryptPassword(String loginName, String password, String salt)
    {
        return new Md5Hash(loginName + password + salt).toHex();
    }

    /**
     * 批量删除分销商信息
     * 
     * @param distributorIds 需要删除的分销商信息主键
     * @return 结果
     */
    @Override
    public int deleteJtDistributorByDistributorIds(String distributorIds)
    {
        return jtDistributorMapper.deleteJtDistributorByDistributorIds(Convert.toStrArray(distributorIds));
    }

    /**
     * 删除分销商信息信息
     * 
     * @param distributorId 分销商信息主键
     * @return 结果
     */
    @Override
    public int deleteJtDistributorByDistributorId(Long distributorId)
    {
        return jtDistributorMapper.deleteJtDistributorByDistributorId(distributorId);
    }
}
